package com.example.Sao.MyActivity;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.Sao.Adapter.DeviceInfoAdpter;
import com.example.Sao.Adapter.HistoryAdapter;
import com.example.Sao.Adapter.HistoryAdaptero;
import com.example.Sao.Adapter.HistoryCallBack;
import com.example.Sao.MyBean.ExploreStause;
import com.example.Sao.MyBean.InfoBean;
import com.example.Sao.MyFragment.LocalDialogFragment;
import com.example.Sao.ObjectBox.DeviceEntity;
import com.example.Sao.ObjectBox.DeviceEntity_;
import com.example.Sao.R;
import com.example.Sao.SqlLite.SQLiteDB;
import com.example.Sao.Tools.ObjectBoxHelper;
import com.example.Sao.Tools.StatusColorUtil;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import io.reactivex.functions.Consumer;

public class SearchActivity extends MyBaseActivity implements HistoryCallBack {
    private DeviceInfoAdpter deviceInfoAdpter;
    private String partment;
//    private CardView noting;
    private final String TAG="SearchActivity";
    private ObjectBoxHelper objectBoxHelper;
    private SQLiteDB sqLiteDB;
    private boolean arrow_stute = true;
    private HistoryAdapter historyAdapter;
    private HistoryAdaptero historyAdaptero;
    private ImageView delete;
    private EditText search_room;
    private AppCompatImageView iv_back;
    private RecyclerView mRecyclerView,search_result;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        EventBus.getDefault().register(this);
        sqLiteDB = SQLiteDB.getInstance(this);
        //设置状态栏颜色
        StatusColorUtil.setColor(this, getResources().getColor(R.color.skyblue));
        initview();
        partment = getIntent().getStringExtra("partment");
        search_room.setHint("搜索"+partment+"的设备");
        objectBoxHelper = ObjectBoxHelper.getInstance();
        if (sqLiteDB.getAll("records").size()<=5&&sqLiteDB.getAll("records").size()>=0) {
            initdata(true);
        }else if (sqLiteDB.getAll("records").size()>=6){
            initdata6(false);
        }
    }
    @Override
    public void historycallback(String historyword) {
        search_room.setText(historyword);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (search_room.getText().toString()!=null&&!"".equals(search_room.getText().toString())){
            objectBoxHelper.RxQuery(search_room.getText().toString(),partment,
                    DeviceEntity_.deviceName,DeviceEntity_.useDepartment)
                    .subscribe(new Consumer<List<DeviceEntity>>() {
                        @Override
                        public void accept(List<DeviceEntity> entities) throws Exception {
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    if (entities.size()>0){
                                        initResultData(entities);
                                    }
                                }
                            },600);
                        }
                    });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(ExploreStause stause) {
        if ("explore_stause".equals(stause.getEvent())){
            if (stause.getisExplore()){
                initdata6(true);
            }else {
                initdata6(false);
            }
        }
    }

    private void initview(){
//        noting = findViewById(R.id.no);
        search_result = findViewById(R.id.seacher_result);
        mRecyclerView  =findViewById(R.id.RecyclerView);
        delete = findViewById(R.id.delete);
        search_room = findViewById(R.id.sech_room);
        iv_back = findViewById(R.id.iv_back);
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sqLiteDB.deleteData("records");
                initdata(true);
            }
        });
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SearchActivity.this.finish();
            }
        });
        search_room.setSelection(search_room.getText().toString().length());
        search_room.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {// 修改回车键功能
                    // 先隐藏键盘
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                                Objects.requireNonNull(getCurrentFocus()).getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
//                    noting.setVisibility(View.GONE);
                    mRecyclerView.setVisibility(View.VISIBLE);
                    search_result.setVisibility(View.GONE);
                    final LocalDialogFragment localDialogFragment = new LocalDialogFragment();
                    localDialogFragment.show(getSupportFragmentManager(),"");
                    objectBoxHelper.RxQuery(search_room.getText().toString(),partment,
                            DeviceEntity_.deviceName,DeviceEntity_.useDepartment)
                    .subscribe(new Consumer<List<DeviceEntity>>() {
                        @Override
                        public void accept(List<DeviceEntity> entities) throws Exception {
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    if (entities.size()>0){
                                        localDialogFragment.dismiss();
                                        initResultData(entities);
                                    }else {
                                        mRecyclerView.setVisibility(View.VISIBLE);
//                                noting.setVisibility(View.VISIBLE);
                                        localDialogFragment.dismiss();
                                        Toast.makeText(SearchActivity.this,"未查询到这条信息",Toast.LENGTH_SHORT).show();
                                    }
                                }
                            },600);
                        }
                    });
                    // 按完搜索键后将当前查询的关键字保存起来,如果该关键字已经存在就不执行保存
                    boolean hasData = sqLiteDB.hasData(search_room.getText().toString().trim().replaceAll("\r|\n*",""));
                    if (!hasData&&!( search_room.getText().toString().equals(""))) {
                        sqLiteDB.insertData("records",search_room.getText().toString().trim());
                    }
                }
                return false;
            }
        });
    }
    private void initdata6(boolean isExplore){
        Log.d("search",new Gson().toJson(sqLiteDB.getAll("records")));
        historyAdapter = new HistoryAdapter(this, sqLiteDB.getAll("records"), isExplore,this);
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(historyAdapter);
    }

    private void initdata(boolean isExplore){
        if (sqLiteDB.getAll("records").size()>0) {
            Log.d("search",new Gson().toJson(sqLiteDB.getAll("records")));
            historyAdaptero = new HistoryAdaptero(this, sqLiteDB.getAll("records"), isExplore,this);
            StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
            mRecyclerView.setLayoutManager(layoutManager);
            mRecyclerView.setAdapter(historyAdaptero);
        }else {
            Log.d("search",new Gson().toJson(sqLiteDB.getAll("records")));
            historyAdaptero = new HistoryAdaptero(this, null, isExplore,this);
            StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
            mRecyclerView.setLayoutManager(layoutManager);
            mRecyclerView.setAdapter(historyAdaptero);
        }
    }

    /**
     * 刷新查询结果的数据
     */
    private void initResultData(List<DeviceEntity>entities){
        mRecyclerView.setVisibility(View.GONE);
        search_result.setVisibility(View.VISIBLE);
        List<InfoBean>list = new ArrayList<>();
        list.add(new InfoBean());
        if (deviceInfoAdpter ==null) {
            DeviceInfoAdpter deviceInfoAdpter = new DeviceInfoAdpter(SearchActivity.this, entities);
            search_result.setLayoutManager(new LinearLayoutManager(SearchActivity.this));
            search_result.setAdapter(deviceInfoAdpter);
        }else {
            deviceInfoAdpter.setInfoBeanList(entities);
            deviceInfoAdpter.notifyDataSetChanged();
        }
    }
}